package cn.rjzjh.tapestry.tams.pages.sys.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONArray;
import org.hibernate.Session;

import cn.rjzjh.commons.util.apiext.CollectionUtil;
import cn.rjzjh.commons.util.callback.IConvertValue;
import cn.rjzjh.commons.util.exception.ProjectException;
import cn.rjzjh.commons.util.web.OperateResult;
import cn.rjzjh.tapestry.busi.constant.UnitType;
import cn.rjzjh.tapestry.busi.model.ca.CaRole;
import cn.rjzjh.tapestry.busi.model.ca.CaRoleAssign;
import cn.rjzjh.tapestry.busi.service.IOrgService;
import cn.rjzjh.tapestry.busi.service.IStaffService;
import cn.rjzjh.tapestry.tams.base.ParentPage;
import cn.rjzjh.tapestry.tams.services.base.IHbService;

public class RoleAssign extends ParentPage {

	@Inject
	private IStaffService staffService;
	@Inject
	private IOrgService orgService;
	@Inject
	private IHbService hbService;
	@Inject
	private Session session;

	@Property
	private List<CaRole> allRoles;
	@Property
	private List<String> selRoleIds;
	@Property
	private Map<String, IConvertValue> convmap;// 转换器

	@Persist(PersistenceConstants.CLIENT)
	private String unitType;// 会通过参数传过来
	@Persist(PersistenceConstants.CLIENT)
	private int objId;

	/***
	 * 保存选择的结果
	 * 
	 * @param selIds
	 * @return
	 */
	@CommitAfter
	@OnEvent(value = "save")
	private OperateResult sava(JSONArray selIds) {
		if (selIds == null) {
			return new OperateResult(0, "需要传入要保存的对象");
		}

		List<CaRole> selRoles = null;
		if ("STAFF".equals(unitType)) {
			selRoles = staffService.findRolesByStaff(objId);
		} else {
			selRoles = staffService.findRolesByUnit(
					UnitType.findByName(unitType), objId, false);
		}
		// 去除开发者
		CollectionUtils.filter(selRoles, new Predicate() {
			@Override
			public boolean evaluate(Object object) {
				CaRole caRole = (CaRole) object;
				return caRole.getId() != 0;
			}
		});

		int[] oriIds = new int[selRoles.size()];
		for (int i = 0; i < oriIds.length; i++) {
			oriIds[i] = selRoles.get(i).getId();
		}
		int[] saveIds = new int[selIds.length()];
		for (int i = 0; i < selIds.length(); i++) {
			saveIds[i] = Integer.parseInt(selIds.getString(i));
		}
		List<Integer> addList = new ArrayList<Integer>();// 新增
		for (int i = 0; i < saveIds.length; i++) {
			if (!ArrayUtils.contains(oriIds, saveIds[i])) {
				addList.add(saveIds[i]);
			}
		}
		if (CollectionUtils.isNotEmpty(addList)) {
			for (Integer roleid : addList) {
				CaRoleAssign saveobj = new CaRoleAssign();
				saveobj.setAssignType(unitType);
				saveobj.setAssignValue(objId);
				saveobj.setCaRole(new CaRole(roleid));
				session.save(saveobj);
			}

		}
		List<Integer> delList = new ArrayList<Integer>();// 删除
		for (int i = 0; i < oriIds.length; i++) {
			if (!ArrayUtils.contains(saveIds, oriIds[i])) {
				delList.add(oriIds[i]);
			}
		}

		if (CollectionUtils.isNotEmpty(delList)) {
			if ("STAFF".equals(unitType)) {
				List<String> saveMinu = new ArrayList<String>();
				for (Integer delId : delList) {
					int delint = hbService
							.getQuery(
									"delete CaRoleAssign where assignType=? and assignValue=? and caRole=?")
							.setParameter(0, unitType).setParameter(1, objId)
							.setParameter(2, new CaRole(delId)).executeUpdate();
					if (delint == 0) {
						saveMinu.add(String.valueOf(delId));
					}
				}

				try {
					// 保存排除的ids
					String saveValue = CollectionUtil.listJoin(saveMinu, "|");
					hbService
							.getQuery(
									"update CaStaff set minusRole=? where id=?")
							.setParameter(0, saveValue).setParameter(1, objId)
							.executeUpdate();

				} catch (ProjectException e) {
				}
			} else {
				hbService
						.getQuery(
								"delete CaRoleAssign where assignType=? and assignValue=? and caRole.id in (:roleIds)")
						.setParameter(0, unitType).setParameter(1, objId)
						.setParameterList("roleIds", delList).executeUpdate();
			}
		}
		return new OperateResult(1, "保存成功");
	}

	/****
	 * 需要分派页面初始化
	 * 
	 * @param unitType
	 *            STAFF 雇员 ,其它对应UnitType枚举类型
	 * @param staffId
	 */
	void onActivate(String unitType, int objId) {
		this.unitType = unitType;
		this.objId = objId;
		allRoles = staffService.findValidRole();
		convmap = new HashMap<String, IConvertValue>();//
		convmap.put("roleName1", I18NConvert);
		if ("STAFF".equals(unitType)) {
			List<CaRole> selRoles = staffService.findRolesByStaff(objId);
			selRoleIds = (List<String>) CollectionUtil.getColFromObj(selRoles,
					"id");
		} else {
			List<CaRole> selRoles = staffService.findRolesByUnit(
					UnitType.findByName(unitType), objId, false);
			selRoleIds = (List<String>) CollectionUtil.getColFromObj(selRoles,
					"id");
		}
	}
}
